package com.example.online.music.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.online.music.common.R;
import com.example.online.music.constant.Constants;
import com.example.online.music.mapper.PayItemMapper;
import com.example.online.music.mapper.PayMapper;
import com.example.online.music.mapper.SongMapper;
import com.example.online.music.model.domain.Pay;
import com.example.online.music.model.domain.PayItem;
import com.example.online.music.model.domain.Song;
import com.example.online.music.model.request.SongRequest;
import com.example.online.music.service.ObjectStoreService;
import com.example.online.music.service.SongService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class SongServiceImpl extends ServiceImpl<SongMapper, Song> implements SongService {

    @Autowired
    private SongMapper songMapper;

    @Autowired
    private PayMapper payMapper;

    @Autowired
    private PayItemMapper payItemMapper;

    @Autowired
    private ObjectStoreService oss;

    @Override
    public R allSong() {
        return R.success(null, songMapper.selectList(null));
    }

    @Override
    public R addSong(SongRequest addSongRequest, MultipartFile mpfile) {
        Song song = new Song();
        BeanUtils.copyProperties(addSongRequest, song);
//        String pic = "/img/songPic/tubiao.jpg";
        String pic = "https://java-pp.oss-cn-hangzhou.aliyuncs.com/img/songPic/1689093435201-tubiao.jpg";
//        String fileName = System.currentTimeMillis() + "-" + mpfile.getOriginalFilename();
        String fileName = mpfile.getOriginalFilename();
//        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song";
//        File file1 = new File(filePath);
//        if (!file1.exists()) {
//            if (!file1.mkdir()) {
//                return R.fatal("创建文件失败");
//            }
//        }
//        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
//        String storeUrlPath = "/song/" + fileName;
        String storeUrlPath = "song";
//        try {
//            mpfile.transferTo(dest);
//        } catch (IOException e) {
//            return R.fatal("上传失败" + e.getMessage());
//        }
        String uploadFileUrl;
        try {
            uploadFileUrl = oss.uploadFile(storeUrlPath, fileName, mpfile);
        } catch (IOException e) {
            return R.fatal("上传失败" + e.getMessage());
        }
        song.setCreateTime(new Date());
        song.setUpdateTime(new Date());
        song.setPic(pic);
        song.setUrl(uploadFileUrl);
        if (songMapper.insert(song) > 0) {
            return R.success("上传成功", storeUrlPath);
        } else {
            return R.error("上传失败");
        }
    }

    @Override
    public R updateSongMsg(SongRequest updateSongRequest) {
        Song song = new Song();
        BeanUtils.copyProperties(updateSongRequest, song);
        if (songMapper.updateById(song) > 0) {
            return R.success("修改成功");
        } else {
            return R.error("修改失败");
        }
    }

    @Override
    public R updateSongUrl(MultipartFile urlFile, int id) {
//        String fileName = System.currentTimeMillis() + "-" + urlFile.getOriginalFilename();
        String fileName = urlFile.getOriginalFilename();
//        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song";
//        File file1 = new File(filePath);
//        if (!file1.exists()) {
//            if (!file1.mkdir()) {
//                return R.fatal("创建目的文件夹失败");
//            }
//        }
//        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
//        String storeUrlPath = "/song/" + fileName;
        String storeUrlPath = "song";
//        try {
//            urlFile.transferTo(dest);
//        } catch (IOException e) {
//            return R.fatal("更新失败" + e.getMessage());
//        }
        String uploadFileUrl;
        try {
            uploadFileUrl = oss.uploadFile(storeUrlPath, fileName, urlFile);
        } catch (IOException e) {
            return R.fatal("更新失败" + e.getMessage());
        }
        Song song = new Song();
        song.setId(id);
        song.setUrl(uploadFileUrl);
        if (songMapper.updateById(song) > 0) {
            return R.success("更新成功", uploadFileUrl);
        } else {
            return R.error("更新失败");
        }
    }

    @Override
    public R updateSongPic(MultipartFile urlFile, int id) {
        String fileName = System.currentTimeMillis() + "-" + urlFile.getOriginalFilename();
//        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "img" + System.getProperty("file.separator") + "songPic";
//        File file1 = new File(filePath);
//        if (!file1.exists()) {
//            if (!file1.mkdir()) {
//                return R.fatal("创建文件夹失败");
//            }
//        }
//
//        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
//        String storeUrlPath = "/img/songPic/" + fileName;
        String storeUrlPath = "img/songPic";

//        try {
//            urlFile.transferTo(dest);
//        } catch (IOException e) {
//            return R.fatal("上传失败" + e.getMessage());
//        }
        String ossUrlPath;
        try {
            ossUrlPath = oss.uploadFile(storeUrlPath, fileName, urlFile);
        } catch (IOException e) {
            return R.fatal("上传失败" + e.getMessage());
        }
        Song song = new Song();
        song.setId(id);
        song.setPic(ossUrlPath);
        if (songMapper.updateById(song) > 0) {
            return R.success("上传成功", storeUrlPath);
        } else {
            return R.error("上传失败");
        }
    }

    @Override
    public R deleteSong(Integer id) {
        //在数据库中删除之前,把OSS中的资源一并删除
        Song song = songMapper.selectById(id);
        oss.deleteFile(song.getUrl());

        if (songMapper.deleteById(id) > 0) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

    @Override
    public R songOfSingerId(Integer singerId) {
        QueryWrapper<Song> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("singer_id", singerId);
        return R.success(null, songMapper.selectList(queryWrapper));
    }

    @Override
    public R songOfId(Integer id) {
        QueryWrapper<Song> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return R.success(null, songMapper.selectList(queryWrapper));
    }

    @Override
    public R songOfSingerName(String name) {
        QueryWrapper<Song> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        return R.success(null, songMapper.selectList(queryWrapper));
    }

    @Override
    public List<Integer> getAllSongIds() {
        return songMapper.selectAllSongIds();
    }

    /**
     * @param userId
     * @Description: 获取用户推荐数据
     * @Author: yang_yong
     * @CreateTime:
     * @return: com.example.online.music.common.R
     */
    @Override
    public R getRecommendSongList(Integer userId) {
        List<Song> songList = null;
        if (null != userId && userId > 0) {
            songList = songMapper.selectAllRecommendSongList(userId);
            if (null != songList && !songList.isEmpty()) {
                return R.success(null, songList);
            }
        }
        songList = songMapper.selectAllSongRankList();
        return R.success(null, songList);
    }

    @Override
    public R isPay(Integer songId, Integer userId) {
        String msg = "查询歌曲支付状态时发生错误";
        try {
            QueryWrapper<PayItem> itemqw = new QueryWrapper<>();
            itemqw.eq("user_id", userId).eq("song_id", songId);
            List<PayItem> payItems = payItemMapper.selectList(itemqw);
            if (payItems == null) {
                return R.error(msg);
            }
            //歌曲未购买
            if (payItems.isEmpty()) {
                return R.warning("该歌曲还未支付");
            }

            //不等于0时，判断支付清单的状态
            QueryWrapper<Pay> payqw = new QueryWrapper<>();
            payqw.eq("trade_no", payItems.get(0).getTradeNo());
            List<Pay> pays = payMapper.selectList(payqw);

            if (pays == null || pays.size() < 1) {
                return R.error(msg);
            }

            if (pays.get(0).getPayStatus().equals(Constants.PAY_STATUS_1)) {
                return R.success("", true);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return R.error(msg);
        }
        return R.fatal(msg);
    }

    @Override
    public R downloadSong(Integer id, Integer userId, HttpServletResponse response) throws Exception {
        String msg = "歌曲下载时发生错误";
        Song song = songMapper.selectById(id);
        if (song == null) {
            return R.error(msg);
        }

//        //下载目标地址
//        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "song";
//        String fileFullName = filePath + System.getProperty("file.separator") + song.getUrl().substring(6);
//
//        //文件后缀
//        String suffix = song.getUrl().substring(song.getUrl().lastIndexOf("."));
//
//        //设置中文文件名与后缀
//        String filename= URLEncoder.encode((song.getName() +suffix),"utf-8").replaceAll("\\+", "%20");
//
//        // 清除buffer缓存
//        response.reset();
//        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
//        response.setHeader("Content-Type", "application/octet-stream");
//        response.setContentType("application/octet-stream; charset=UTF-8");
//
//        try(InputStream is = new FileInputStream(new File(fileFullName));
//            OutputStream data = response.getOutputStream()) {
//            // 5M一次读写
//            byte[] buffer = new byte[1024 * 1024 * 5];
//            int len;
//            while ((len = is.read(buffer)) != -1) {
//                data.write(buffer, 0, len);
//            }
//        } catch (Exception oe) {
//            oe.printStackTrace();
//            return R.error(msg);
//        }
        // 使用oss的下载功能将OSS中的文件下载到浏览器的下载目录下

        String userHomeDir = System.getProperty("user.home");
        String songUrl = song.getUrl();
        String downloadDir = userHomeDir + "/OnlineMusic/Song/";
        oss.downloadFile(songUrl,downloadDir);



        return R.success("下载成功");
    }
}
